import React from 'react';
import { render } from 'react-dom';
import { createStore } from 'redux';
import { Provider, connect } from 'react-redux';
import '../css/counter.css';

// 计数器
// 定义ui组件
class Counter extends React.Component {
  render() {
    const { value, onAdd, onMinus} = this.props;
    return (
      <div className="num">
        <h3>一个计数器的简单demo</h3>
        <button onClick={onMinus}>减</button>
        <span>{value}</span>
        <button onClick={onAdd}>加</button>
      </div>
    )
  }
}
//定义初始的state映射到props，子组件可以取到这个state，
// ownProps是定义在<App />上的属性
function mapStateToProps(state,ownProps) {
  return {
    value: state.count + ownProps.unit
  }
}
//定义初始的dispatch映射到props，子组件可以取到这个dispatch，
function mapDispatchToProps(dispatch, ownProps) {
  return {
    onAdd: () => dispatch({...addAction, perload: ownProps.num}),
    onMinus: () =>dispatch({...MinusAction, perload: ownProps.num})
  }
}
// 定义action
const addAction = {
  type: 'add'
}
const MinusAction = {
  type: 'minus'
}
// 用react-redux里的connect，把ui组件生成容器组件，
const App = connect(mapStateToProps, mapDispatchToProps)(Counter);

// reducer
function counter(state = {count:0}, action) {
  switch (action.type) {
    case 'add':
      return {count: state.count+action.perload}
    case 'minus':
      return {count: state.count-action.perload}
    default :
    return state
  }
}
// 状态仓库store
const store =createStore(counter);
// 渲染到页面，需要把<App />放在provider组件里面，这样可以取到store，并传递到子组件中去
render(
  <Provider store={store}>
    <App unit=" 元" num={10}/>
  </Provider>,
  document.getElementById('app')
)